﻿/**
 * @file SoundSource.h
 * @author Yunfeng.Bo (Yunfeng.Bo@qq.com)
 * @brief Qt5 QAudioOutput + QIODevice 播放固定频率的声音
 * @version 0.1
 * @date 2022-09-13
 *
 * @copyright Copyright (c) 2022
 *
 */

#pragma once

#define SAMPLE_RATE 44100
#define SAMPLE_COUNT (SAMPLE_RATE * 0.5) /* 0.5 seconds */
#define AMPLITUDE (1.0 * 0x7F00)
#define ONE_HZ (1.0 / SAMPLE_RATE)

#include <QAudioFormat>
#include <QAudioOutput>
#include <QIODevice>
#include <QObject>

class SoundSource : public QIODevice {
public:
    SoundSource();
    SoundSource(int fq, int vol);

    // 设置声音频率
    void set_frequency(int fq);
    // 设置音量
    void set_volume(int vol);
    // 设置播放最小时长，单位 seconds
    void set_interval(double interval);

    void start();
    void stop();

protected:
    virtual qint64 readData(char* data, qint64 maxlen);
    virtual qint64 writeData(const char* data, qint64 len);

private:
    QAudioFormat default_format() {
        QAudioFormat audioFormat;
        audioFormat.setCodec("audio/pcm");
        audioFormat.setByteOrder(QAudioFormat::LittleEndian);
        audioFormat.setSampleRate(SAMPLE_RATE);
        audioFormat.setChannelCount(2);
        audioFormat.setSampleSize(16);
        audioFormat.setSampleType(QAudioFormat::SignedInt);
        return audioFormat;
    }

    void append_data();

private:
    QAudioOutput* audio;
    
    double m_frequency;
    double m_volume;
    double m_interval;

    qint64 m_it;

    QList<char> m_data;
};